package com.hemaapp.yjnh.fragment;

import java.util.ArrayList;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.util.XtomWindowSize;
import xtom.frame.view.XtomListView;
import xtom.frame.view.XtomRefreshLoadmoreLayout;
import xtom.frame.view.XtomRefreshLoadmoreLayout.OnStartListener;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.uu.view.UUHorizonalScrollView;
import com.hemaapp.yjnh.activity.ImageCarouselHeadClickListener;
import com.hemaapp.yjnh.activity.CmnProductionListActivity;
import com.hemaapp.yjnh.activity.CodeCaptureActivity;
import com.hemaapp.yjnh.activity.CunyouActivity;
import com.hemaapp.yjnh.activity.FarmerActivity;
import com.hemaapp.yjnh.activity.LandMarkActivity;
import com.hemaapp.yjnh.activity.LaokeActivity;
import com.hemaapp.yjnh.activity.LeleActivity;
import com.hemaapp.yjnh.activity.AgriculturalDemandActivity;
import com.hemaapp.yjnh.activity.NoticeListActivity;
import com.hemaapp.yjnh.activity.OrganicActivity;
import com.hemaapp.yjnh.activity.SearchActivity;
import com.hemaapp.yjnh.activity.SpecialtyActivity;
import com.hemaapp.yjnh.activity.SpeechActivity;
import com.hemaapp.yjnh.activity.WebviewActivity;
import com.hemaapp.yjnh.activity.ZouzouActivity;
import com.hemaapp.yjnh.adapter.FarmerListAdapter;
import com.hemaapp.yjnh.bean.AdImage;
import com.hemaapp.yjnh.bean.Blog;
import com.hemaapp.yjnh.bean.Client;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.ProvinceCityDistrict;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseApplication;
import com.hemaapp.yjnh.BaseFragment;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.db.CityDBClient;
import com.hemaapp.yjnh.utils.ImageUtils;
import com.hemaapp.yjnh.utils.LoginUtil;
import com.hemaapp.yjnh.view.GuideDialog;
import com.hemaapp.yjnh.view.ImageCarouselBanner;

/**首页
 * @author GuiyouZhang
 * Date：2015年12月30日 下午3:25:09
 * Email:guiyouzhang@163.com
 */
public class HomePageFragment extends BaseFragment implements OnClickListener{

	private static final int REQUEST_NOTICE = 0x01;//通知消息发生了改变
	
	private ImageButton titleLeft;
	private TextView tv_search_hint;
	private ImageView title_audio;
	private ImageView title_msg;

	private RefreshLoadmoreLayout parentLayout;
	private View headerView;
	private ImageCarouselBanner imageCarouselBanner;
	private UUHorizonalScrollView recommode_goods_scroll;
	private LinearLayout ll_recommend_goods;//推荐商品布局
	private TextView tvDepot;
	private TextView tvFarmer;
	private TextView tvLele;
	private TextView tvZouzou;
	private TextView tvCunyou;
	private TextView tvOrganic;
	private TextView tvLandmark;
	private TextView tvSpecialty;
	private TextView tvCrowdfunding;
	private TextView tvAgricultural;
	private TextView tvMoreGoods;
	private XtomListView listview;//推荐田家
	private LinearLayout ll_return_top;

    private LoginUtil.LoginCallBack loginCallBack;
	private ArrayList<AdImage> imgs = new ArrayList<>();
	private ArrayList<Blog> recommendGoods = new ArrayList<Blog>();//推荐商品
	private ArrayList<Client> recommendClients = new ArrayList<>();//推荐田家
	private int curPage = 0;
	private FarmerListAdapter farmerListAdapter;
	private int recPicWide ;//推荐商品图片的宽度
	private int recPicHei ;//推荐商品图片的高度
    private int groupWide = 0;//推荐商品每一组数据的宽度
    private int groupNum = 3;//根据手机屏幕不同需要显示的推荐商品组的数量也不一样，最少3个
    private int screenWide = 0;//当前屏幕的宽度
    private Activity activity;
    private int ten = 10;
    private User user;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.fragment_homepage);
		activity = getActivity();
		ten = BaseUtil.dip2px(activity, 10);
		user = BaseApplication.getInstance().getUser();
		super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
		screenWide = XtomWindowSize.getWidth(getActivity());
		init();
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		if (hidden) {
			imageCarouselBanner.stopShow();
            loginCallBack = null;
		}else {
			imageCarouselBanner.startShow();
		}
		super.onHiddenChanged(hidden);
	}

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

	private void init() {
		//初始化listivew的header部分
		headerView = LayoutInflater.from(getActivity()).inflate(R.layout.header_fragment_homepage, null);
		findHeaderViews();
		listview.addHeaderView(headerView);
		getADList();
		getSuperValueList();
		getClientList();//
        if (user != null)
            getNetWorker().clientLogin();
	}
	
	/**获取广告列表
	 * 
	 */
	private void getADList() {
		getNetWorker().indexadList();
	}
	
	/**获取粮票超值
	 * 
	 */
	private void getSuperValueList() {
		getNetWorker().blogList("1", "0", "1", "1", "", "", "", "", "", "", "", "", "", "", "0");
	}
	
	/**获取首页推荐田家
	 * 
	 */
	private void getClientList() {
		String token = "";
		if (null != user) {
			token = user.getToken();
		}
		getNetWorker().clientList(token, "1", "0", "1", "1", "", curPage+"", "", "");
	}

	/**判断是否有未读消息
	 * 
	 */
	private void checkUnreadMsg() {
        if (user != null && !isNull(user.getNoticecount()) && !user.getNoticecount().equals("0")) {
            title_msg.setImageResource(R.mipmap.title_msg_unread);
        } else
            title_msg.setImageResource(R.mipmap.title_msg_no);
    }

    @Override
	protected void callBeforeDataBack(HemaNetTask netTask) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
            case INDEXAD_LIST:
            case BLOG_LIST:
            case CLIENT_LIST:
            case DISTRICT_LIST:
			showProgressDialog("请稍候");
            default:
                break;
		}
	}

	@Override
	protected void callAfterDataBack(HemaNetTask netTask) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
            case INDEXAD_LIST:
            case BLOG_LIST:
            case CLIENT_LIST:
            case DISTRICT_LIST:
			    cancelProgressDialog();
            default:
                break;
		}
	}

	@Override
	protected void callBackForServerSuccess(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
            case INDEXAD_LIST:
                HemaPageArrayResult<AdImage> aResult = (HemaPageArrayResult<AdImage>) baseResult;
                if (aResult == null || aResult.getObjects() == null)
                    return;
				imgs.clear();
                imgs.addAll(aResult.getObjects());
                initPager();
                break;
            case BLOG_LIST:
                HemaPageArrayResult<Blog> bResult = (HemaPageArrayResult<Blog>) baseResult;
                if (bResult == null || bResult.getObjects() == null)
                    return;
                recommendGoods.clear();
                recommendGoods = bResult.getObjects();
                setGoods();
                break;
            case CLIENT_LIST:
                HemaPageArrayResult<Client> cResult = (HemaPageArrayResult<Client>) baseResult;
                if (cResult == null || cResult.getObjects() == null)
                    return;
                ArrayList<Client> clients = cResult.getObjects();
                if (curPage == 0) {// 刷新
                    parentLayout.refreshSuccess();
                    recommendClients.clear();
                    recommendClients.addAll(clients);
                } else {
                    parentLayout.loadmoreSuccess();
                    if (clients.size() > 0)
                        this.recommendClients.addAll(clients);
                    else {
                        parentLayout.setLoadmoreable(false);
                        XtomToastUtil.showShortToast(getActivity(), "已经到最后啦");
                    }
                }
                refreshHomePage(-1);
                //显示引导
                if (BaseUtil.checkVirgin(getActivity())) {
                    GuideDialog guideDialog = new GuideDialog(getActivity());
                    guideDialog.builder(BaseApplication.getInstance().getSysInitInfo().getWelcome_content()).show();
                }
                break;
            case CLIENT_LOGIN:
                HemaArrayResult<User> uResult = (HemaArrayResult<User>) baseResult;
                user = uResult.getObjects().get(0);
                BaseApplication.getInstance().setUser(user);
                checkUnreadMsg();
                break;
            default:
                break;
        }
    }

	@Override
	protected void callBackForServerFailed(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case INDEXAD_LIST:
            case BLOG_LIST:
            case CLIENT_LIST:
                if (curPage == 0) {
                    parentLayout.refreshFailed();
                } else {
                    parentLayout.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(activity, "获取信息失败，" + baseResult.getMsg());
                break;
            case CLIENT_LOGIN:
                checkUnreadMsg();
                break;
        }
    }

	@Override
	protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case INDEXAD_LIST:
            case BLOG_LIST:
            case CLIENT_LIST:
                if (curPage == 0) {
                    parentLayout.refreshFailed();
                } else {
                    parentLayout.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(activity, "获取信息失败，请稍后再试");
                refreshHomePage(failedType);
                break;
            case CLIENT_LOGIN:
                checkUnreadMsg();
                break;
        }
    }
	
	private void refreshHomePage(int failedType) {
		if (null == farmerListAdapter) {
			farmerListAdapter = new FarmerListAdapter(getActivity(), recommendClients);
			farmerListAdapter.setEmptyString("暂时没有推荐田家");
			listview.setAdapter(farmerListAdapter);
		}else {
			farmerListAdapter.notifyDataSetChanged();
		}
		farmerListAdapter.setFailtype(failedType);
	}

	@Override
	protected void findView() {
		titleLeft = (ImageButton) findViewById(R.id.title_left_btn);
		tv_search_hint = (TextView) findViewById(R.id.tv_search_hint);
		title_audio = (ImageView) findViewById(R.id.title_audio);
		title_msg = (ImageView) findViewById(R.id.title_msg);

		parentLayout = (RefreshLoadmoreLayout) findViewById(R.id.refreshLoadmoreLayout);
		listview = (XtomListView) findViewById(R.id.listview);
		ll_return_top = (LinearLayout) findViewById(R.id.ll_return_top);//回到顶部
	}
	
	private void findHeaderViews() {
		imageCarouselBanner = (ImageCarouselBanner) headerView.findViewById(R.id.image_carousel_banner);
		recommode_goods_scroll = (UUHorizonalScrollView) headerView.findViewById(R.id.recommode_goods_scroll);
		ll_recommend_goods = (LinearLayout) headerView.findViewById(R.id.layout_recommend_goods);
		tvDepot = (TextView)headerView.findViewById( R.id.tv_depot );
		tvFarmer = (TextView)headerView.findViewById( R.id.tv_farmer );
		tvLele = (TextView)headerView.findViewById( R.id.tv_lele );
		tvZouzou = (TextView)headerView.findViewById( R.id.tv_zouzou );
		tvCunyou = (TextView)headerView.findViewById( R.id.tv_cunyou );
		tvOrganic = (TextView)headerView.findViewById( R.id.tv_organic );
		tvLandmark = (TextView)headerView.findViewById( R.id.tv_landmark );
		tvSpecialty = (TextView)headerView.findViewById( R.id.tv_specialty );
		tvCrowdfunding = (TextView)headerView.findViewById( R.id.tv_crowdfunding );
		tvAgricultural = (TextView)headerView.findViewById( R.id.tv_agricultural );
		tvMoreGoods = (TextView)headerView.findViewById( R.id.tv_more_recommod );

		tvDepot.setOnClickListener(this);
		tvFarmer.setOnClickListener(this);
		tvLele.setOnClickListener(this);
		tvZouzou.setOnClickListener(this);
		tvCunyou.setOnClickListener(this);
		tvOrganic.setOnClickListener(this);
		tvLandmark.setOnClickListener(this);
		tvSpecialty.setOnClickListener(this);
		tvCrowdfunding.setOnClickListener(this);
		tvAgricultural.setOnClickListener(this);
		tvMoreGoods.setOnClickListener(this);
	}

	/**显示推荐的商品
	 * 
	 */
	private void setGoods() {
		groupWide = 0;
		//动态添加多个商品
		if (ll_recommend_goods.getChildCount() != 0) {
			ll_recommend_goods.removeAllViews();
		}
		for (int j = 0; j < groupNum; j++) {
			for (int i = 0; i < recommendGoods.size(); i++) {
				Blog blog = recommendGoods.get(i);
				View view = LayoutInflater.from(getActivity()).inflate(
						R.layout.layout_recommend_goods, ll_recommend_goods, false);
				ItemViewHolder ivHolder = new ItemViewHolder();
				itemFindView(view, ivHolder);
				setItem(i, blog, view, ivHolder);
				if (j == 0) {
					view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
	                        MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
					groupWide += view.getMeasuredWidth();
				}
				view.setTag(blog);
				view.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						Blog blog1 = (Blog) v.getTag();
						Intent intent = BaseUtil.createBlogIntent(getActivity(), blog1.getType());
						intent.putExtra("blog_id", blog1.getId());
						startActivity(intent);
					}
				});
			}
			if (j == 0 && groupWide > 0) {
				if (groupWide < screenWide) {
					groupNum = 1;
				} else {
					groupNum += (screenWide / groupWide);
				}
			}
		}
		recommode_goods_scroll.setGroupWide(groupWide);
	}

	@Override
	protected void setListener() {
		titleLeft.setOnClickListener(this);
		tv_search_hint.setOnClickListener(this);
		title_audio.setOnClickListener(this);
		parentLayout.setOnStartListener(new StartListener());
		ll_return_top.setOnClickListener(this);
		title_msg.setOnClickListener(this);
	}

	private void initPager() {
		ArrayList<String> urls = new ArrayList<>();
		for (AdImage item : imgs) {
			urls.add(item.getImgurl());
		}
        imageCarouselBanner.getLayoutParams().height = screenWide/2;
		imageCarouselBanner.onInstance(getActivity(), urls, R.drawable.ad_show_indicator,
                new ImageCarouselHeadClickListener(getActivity(), imgs, "1"));
	}

	private class ItemViewHolder {
		private ImageView backImage;
		private TextView name;
		private TextView price;
		private TextView oldPrice;
	}
	
	private void itemFindView(View view, ItemViewHolder ivHolder) {
		ivHolder.backImage = (ImageView) view.findViewById(R.id.iv_goods);
		ivHolder.name = (TextView) view.findViewById(R.id.tv_name);
		ivHolder.price = (TextView) view.findViewById(R.id.tv_price);
		ivHolder.oldPrice = (TextView) view.findViewById(R.id.tv_old_price);
	}
	
	private void setItem(int i, Blog child, View view, ItemViewHolder ivHolder) {
        ImageUtils.loadBigImage(getActivity(), child.getImgurl(), ivHolder.backImage);
		ivHolder.name.setText(child.getName());
		ivHolder.price.setText("¥"+child.getPrice());
		ivHolder.oldPrice.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG ); //中间横线
		ivHolder.oldPrice.setText("¥"+child.getOldprice());
		ll_recommend_goods.addView(view);
	}
	
	private class StartListener implements OnStartListener {

		@Override
		public void onStartRefresh(XtomRefreshLoadmoreLayout v) {
			curPage = 0;
			getADList();
			getSuperValueList();
			getClientList();//
		}

		@Override
		public void onStartLoadmore(XtomRefreshLoadmoreLayout v) {
			curPage++;
			getClientList();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_left_btn://扫一扫
			Intent itScan = new Intent(getActivity(), CodeCaptureActivity.class);
			startActivity(itScan);
			break;
		case R.id.tv_search_hint:
			Intent itSearch = new Intent(getActivity(), SearchActivity.class);
			itSearch.putExtra("type", 8);
			itSearch.putExtra("assort", "粮库");
			startActivity(itSearch);
			break;
		case R.id.title_audio:
			Intent itSpeech = new Intent(getActivity(), SpeechActivity.class);
			startActivity(itSpeech);
			break;
		case R.id.title_msg:
            loginCallBack = new LoginUtil.LoginCallBack() {
                @Override
                public void onLogin() {
                    Intent intent = new Intent(getActivity(), NoticeListActivity.class);
                    startActivityForResult(intent, REQUEST_NOTICE);
                    loginCallBack = null;
                }
            };
            LoginUtil.getInstance(getActivity(), loginCallBack);
			break;
		case R.id.ll_return_top:
			listview.setSelection(0);
			break;
		case R.id.tv_depot://粮库
			Intent itLiangku = new Intent(getActivity(), LaokeActivity.class);
			startActivity(itLiangku);
			break;
		case R.id.tv_farmer://田家
			Intent itFarmer = new Intent(getActivity(), FarmerActivity.class);
			startActivity(itFarmer);
			break;
		case R.id.tv_lele://乐乐
			Intent itLele = new Intent(getActivity(), LeleActivity.class);
			startActivity(itLele);
			break;
		case R.id.tv_zouzou://走走
			Intent itZouzou = new Intent(getActivity(), ZouzouActivity.class);
			startActivity(itZouzou);
			break;
		case R.id.tv_cunyou://村游
			Intent itCunyou = new Intent(getActivity(), CunyouActivity.class);
			startActivity(itCunyou);
			break;
		case R.id.tv_organic://有机
			Intent itOrganic = new Intent(getActivity(), OrganicActivity.class);
			startActivity(itOrganic);
			break;
		case R.id.tv_landmark://地标
			Intent itLandMark = new Intent(getActivity(), LandMarkActivity.class);
			startActivity(itLandMark);
			break;
		case R.id.tv_specialty://特产
			Intent itSpecialty = new Intent(getActivity(), SpecialtyActivity.class);
			startActivity(itSpecialty);
			break;
		case R.id.tv_crowdfunding://众农
			Intent itZN = new Intent(getActivity(), WebviewActivity.class);
			itZN.putExtra("parm", "zhongnong");
			itZN.putExtra("type", 10);
			startActivity(itZN);
			break;
		case R.id.tv_agricultural://农需
			Intent itMoreFunction = new Intent(getActivity(), AgriculturalDemandActivity.class);
			startActivity(itMoreFunction);
			break;
		case R.id.tv_more_recommod://粮票超值
			Intent it = new Intent(getActivity(), CmnProductionListActivity.class);
			it.putExtra("title", "粮票超值");
			it.putExtra("keytype", "1");
            it.putExtra("keyid", "0");
			it.putExtra("keyword", "");
			it.putExtra("saleflag", "");
			it.putExtra("topflag", "");
			it.putExtra("cheapflag", "");
			it.putExtra("score_percent", "");
			it.putExtra("seller_id", "");
			it.putExtra("district_name", "");
			startActivity(it);
			break;
		default:
			break;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (Activity.RESULT_OK != resultCode) {
			return;
		}
		switch (requestCode) {
		case REQUEST_NOTICE:// 消息通知
			getNetWorker().clientLogin();
			break;
		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Subscribe
	public void onEventMainThread(EventBusMsg msg) {
        if (msg.getType() == EventBusConfig.USER) {
            this.user = msg.getUser();
            if (loginCallBack != null)
                loginCallBack.onLogin();
            checkUnreadMsg();
        }else if (msg.getType() == EventBusConfig.NEW_MSG) {//有新消息
            title_msg.setImageResource(R.mipmap.title_msg_unread);
        }
	}
}
